$(document).ready(function() {
  /*Hide Div*/   
  jQuery("#StoreGmap, #SelectedBr, #SummaryBtn, #ListofBrtxt, #ListofBr, .storeinfobranchlocontyv a, .storeinfobuttcont2yv").hide();
 
  var current_pos = getCookie("current_pos");
  if (current_pos > 1) {
  //alert(current_pos + "TRUE");
    if(current_pos=="2") {
    jQuery("div.wizard a:nth-of-type(1)").attr("class","current done");
    jQuery("div.wizard a:nth-of-type(2)").attr("class","current");
    jQuery("div.wizard a:nth-of-type(3), div.wizard a:nth-of-type(4), div.wizard a:nth-of-type(5)").removeAttr("href");
    }
    if(current_pos=="3") {
    jQuery("div.wizard a:nth-of-type(1), div.wizard a:nth-of-type(2)").attr("class","current done");
    jQuery("div.wizard a:nth-of-type(3)").attr("class","current");
    jQuery("div.wizard a:nth-of-type(4), div.wizard a:nth-of-type(5)").removeAttr("href");
    }
    if(current_pos=="4") {
    jQuery("div.wizard a:nth-of-type(1), div.wizard a:nth-of-type(2),div.wizard a:nth-of-type(3)").attr("class","current done");
    jQuery("div.wizard a:nth-of-type(4)").attr("class","current");
    jQuery("div.wizard a:nth-of-type(5)").removeAttr("href");
    }
    if(current_pos=="5") {
    jQuery("div.wizard a:nth-of-type(1),div.wizard a:nth-of-type(2),div.wizard a:nth-of-type(3),div.wizard a:nth-of-type(4)").attr("class","current done");
    jQuery("div.wizard a:nth-of-type(5)").attr("class","width100 current");
    }
  } else {
    //alert(current_pos + "FALSE");
    jQuery("div.wizard a:nth-of-type(1), div.wizard a:nth-of-type(2), div.wizard a:nth-of-type(3), div.wizard a:nth-of-type(4), div.wizard a:nth-of-type(5)").removeAttr("href");
  } 

  /* Select Near Branch*/
  jQuery("#btn_NearBr").click(function(){
    //jQuery(".storeinfoparticipatingyvhider").hide(); /* hide preferred branch option div */
    jQuery("#StoreGmap, #ListofBrtxt, #ListofBr").show();
    jQuery(".storeinfobranchlocontyv a, #SelectedBr, #SummaryBtn").hide();
    var $locator="nearmap";
    jQuery(".storeinfogmapholdyv").attr("id",$locator);
    //jQuery("#StoreGmap").attr("id",$id);
    loadMap($locator);
    resizeIframe();
   $( "#tabsyv" ).tabs();
  scrollFrameHeight('500');
  });

  /* Select Preferred Branch*/
  jQuery("#btn_PrefBr").click(function() {
    //jQuery(".storeinfoparticipatingyvhider").show();
    jQuery(".storeinfogmapholdyv").removeAttr("id");
    jQuery(".storeinfobranchlocontyv a").show();
    jQuery(".storeinfogmapholdyv, #StoreGmap, #ListofBrtxt, #ListofBr, #SelectedBr, #SummaryBtn").hide();
    scrollFrameHeight('100');
  });
  
  /* Select Region*/
  $('div.storeinfobranchlocontyv a').click(function () {  
    var $this = $(this);
      $this.siblings().removeClass('active');
    if ($this.hasClass('active')) {
      $this.removeClass('active');  
      jQuery(".storeinfogmapholdyv, #StoreGmap, #ListofBrtxt, #ListofBr, #SelectedBr, #SummaryBtn").hide();
      return false;
    } else {
      $this.addClass('active');
      jQuery("#SelectedBr, #SummaryBtn").hide();
      jQuery("#ListofBrtxt, #ListofBr, #StoreGmap").show();
      jQuery(".storeinfogmapholdyv").removeAttr("id");
      var $id="prefmap";
      jQuery(".storeinfogmapholdyv").attr("id",$id);
      loadMap($id);
    resizeIframe();
    $( "#tabsyv" ).tabs();
    scrollFrameHeight('800');
    }
  });
  
  /* Select Store*/
  jQuery('#storescontentlist').on("click", ".storeinfolist11yv, .storeinfolist11yv2", function () {
    showStore(this);
    scrollFrameHeight('800');
    resizeIframe();
  });
  
  if(/globestore/.test(self.location.href)){
     var mode = getCookie("mode");
     var globestore = getCookieR("globestore");
       if(mode=="edit"){
         jQuery(".storeBox").addClass("active");
         jQuery('#globestore').text(globestore);
         jQuery('#ordersum').text("Save");
       }
  }

  jQuery('#btn_OrderSumm').click(function () {
    document.cookie="current_pos=" + "6" + "; path=/";
    resizeIframe();
  });
   


}); /*  .   .   .   . End document ready  .   .   .   .  */

   function getCookieR(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
   }


function loadMap(loc) {
    //alert("no");
  /*. . . . . . . ./

  /*. . . . . . . .*/
  var resp = " ", globestore  ,region=" " ;
  if(loc =="nearmap"){ 
    // . .  [1] Get params
    var province = $("span#province").text(), bg=" ", ar = " " , tn = " ", cy=" "; 
    console.log(province);
    var foundmatch = province.match(/Metro Manila/); // if foundmatch is null province is not metro manila 
    //console.log("Province "+province + "check if metromanila " + foundmatch ); // . . [Debugs]  
    // . .  [2] Check if province value MetroManila or not
     if( foundmatch !== undefined ||  foundmatch !== null || province === "Metro Manila" || province =="Metro Manila"){    
        // true if this is metro manila     
        ar = " ";
        bg = $("span#area").text();
        cy =  $("span#city").text();  
        console.log("@ metromanila condition");
        console.log("cy " + cy + " bg "+bg);      
     } 
     else{
        ar = $("span#area").text();
        bg = " "; 
        tn = $("span#city").text();      
     } 
     console.log(" p "+ province +" b "+ bg + " area " + ar+ " city " + cy +" town " + tn); 
     $.post( baseurl + "globestore/storelocator", { isAjax:"true", city: cy , brgy : bg , area : ar, town: tn, locator : 'nearest' , region: ''  }, function( data,status ) {
        // . . [3] Ajax Service to globestore controller  
        if(status == "success"){    
        //console.log(data); console.log("- - - - - - - - - - - - - - - - - - - ");
          
              try{ 
                  var resp = JSON.parse(data);
                  //console.log("Check JSON");
                  //console.log(resp);
                  lat = resp[0].Lat;
                  long = resp[1].Lng;
                  stores = resp[2].stores;          
                }catch(e){
                  stores = resp.stores;                     
                }

        console.log(" search "); console.log(lat + " - "+ long ); console.log(resp.stores)
        var zoom = 12, dis = 0 ; /* . .  default zoom level  . . */
         
         try{                               
              $(stores).each(function(){
                 if(this.distance > dis){
                  dis = this.distance;
                 }
              });
              // . . [Notes] Fix zoom level
              if(dis > 7){
                zoom = 5; 
              }

          }
         catch(err){  
             /* type 2 json format object json : for loc/clientadd not in db */ 
             //console.log("format 2 NEAREST");
             //var client = new google.maps.LatLng(lat,long); 
             //putMarkers( stores, map);  
             //console.log("inside  error");
         }
         // . . [Notes] Resetting the store map 
         $("#"+loc).removeAttr("style");  
         $("#"+loc).attr("style","height:290px;width:665px;");
         
         // . . Configuring Call to Map 
         client = new google.maps.LatLng(lat,long); 
         map = new google.maps.Map(document.getElementById(loc),{
              zoom: zoom,
              center: client,
              mapTypeId: google.maps.MapTypeId.ROADMAP
         });    
          
        // []        
        putMarkers(stores, map);  
       
      } /* end if status = success */
       putMarkers(stores, map);    
    }); //post  
    
   }
   else if(loc =="prefmap"){
        


    /* query all globe store long lat ajax */
     reg = $("a.storeinfobranchlocyv.active").text(); var g ; 
     $.post( baseurl + "globestore/storelocator", { isAjax:"true", city: ' ' , brgy : ' ' , area :' ' ,town:' ', locator : 'preferred', region : reg  }, function( data,status ) {
      if(status == "success"){

        resp = JSON.parse(data); 
        console.log(" @preferred ");
        console.log(resp);
        console.log(" = = = = = = = = = = = = = = = ");
        
        var ag = parseInt((resp.length /2) ) ; console.log("Avg" + ag);
        console.log(resp[ag]); // getting center of map 
        var cen = resp[ag]; console.log(cen);
        centerstore = new google.maps.LatLng(resp[ag].Latitude,resp[ag].Longitude); 

        $("#"+loc).removeAttr("style");  
        $("#"+loc).attr("style","height:290px;width:665px;");
                    
          map = new google.maps.Map(document.getElementById(loc), {
              zoom: 7,
              center:centerstore,
              mapTypeId: google.maps.MapTypeId.ROADMAP
          });    
          putMarkers(resp, map);  
        
                  
      }// end ifstatus success      
    });  
     
  } //end preferred branch
}

function putMarkers(stores, map){
    //console.log("@putMarkers");console.log(stores);
    var marker, i=0;
    var infowindow = new google.maps.InfoWindow();
    //console.log(map );
    //console.log(stores);
    $(stores).each(function(inc,d){
      console.log("putmarker");
       //console.log(d.Latitude + " " + d.Longitude + " " + d.StoreName + " " + inc);
       image = baseurl.replace("index.php/","skin/images/icons/mapmarker.png");
       marker = new google.maps.Marker({
            zoom: 5,
            position: new google.maps.LatLng(d.Latitude,d.Longitude),
            map: map,
            icon: image
       });
    
      google.maps.event.addListener(marker, 'click', (function(marker, inc) { 
          return function(){
              infowindow.setContent(d.StoreName);
              infowindow.open(map, marker);
              showThisStore(inc);
          }
      })(marker, inc));  
     
   }); //each

   // populate list below for store data
    populateStoreList(stores);
    $( "#tabsyv" ).tabs();

  $("li.margleft7yv a.effecttoggleyv , li.margleft7yv a, a.effecttoggleyv.ui-tabs-anchor").click(function(e){
      var pageclicked = $(this).parent().html();
      var page = $(pageclicked).attr("tabindex");
      pagination(page);
      e.preventDefault();
  });
} // end putMarkers

function showThisStore(storeId){
  storeId = "#store-" + storeId;
  console.log(storeId);
  showStore(jQuery(storeId));
  
}

function showStore(jsObj) {
	scrollFrameHeight('600');
    jQuery("#SelectedBr, #SummaryBtn").show(); 
    jQuery("#ListofBrtxt, #ListofBr").hide();
    jQuery(".storeBox").addClass("active");
    
    // Populate clicked item on shown div
  document.cookie="globestore=" + jQuery(".StoreName",jsObj).text() + "; path=/";
  document.cookie="globestoreid=" + jQuery(".StoreName",jsObj).attr('id') + "; path=/";
  jQuery("#globestore").text(jQuery(".StoreName",jsObj).text());
    jQuery("#selectedstorename").text(jQuery(".StoreName",jsObj).text());
    jQuery("#selectedstoreaddress").text(jQuery(".StoreAddress",jsObj).text());
    storehours = jQuery(jsObj).attr('storehours');
    if(storehours.length>0) {
      jQuery("#selectedstorehours").text(storehours);
      jQuery("#selectedstorehourslabel").show();
    } else {
      jQuery("#selectedstorehours").text("");
      jQuery("#selectedstorehourslabel").hide();      
    }
    
    // Shift map center
    console.log("@showStore");
    lat = jQuery(jsObj).attr('lat');
    long = jQuery(jsObj).attr('long');
    console.log(lat); console.log("= = = = = = "); console.log(Long);
    var laLatLng = new google.maps.LatLng(lat, long);
    
    console.log("lat: " + lat + " long: " + long);
      map.panTo(laLatLng);
      map.setZoom(12);
}

function populateStoreList(stores){
  var ctr, tabctr = 1;
  var divHtml='<div id="tabsyv-1" class="effectyv">';
  var liHtml='<li class="margleft7yv"><a class="effecttoggleyv" href="#tabsyv-1"></a></li>';
  // Loop in div to create
    jQuery(stores).each(function(inc,d){

      //console.log(inc);
      ctr = inc + 1;
        console.log(d.Latitude + " " + d.Longitude + " " + d.StoreName + " " + inc);

        rowClass = (ctr%2==0) ? 'storeinfolist11yv2' : 'storeinfolist11yv';
        
        divHtml += '<div id="store-'+inc+'" class="'+rowClass+'" StoreHours="'+d.StoreHours+'" StoreArea="'+d.StoreArea+'" distance="'+d.distance+'" lat="'+d.Latitude+'" long="'+d.Longitude+'">';
        divHtml += '<a class="StoreName storeinfolist11listyv" href="#" id="'+d.StoreId+'">'+d.StoreName+'</a>';
        divHtml += '<p class="StoreAddress text14reg">'+d.StoreAddress+'</p>';
        divHtml += '</div>';
        
        // if tabctr == 4
        if(ctr % 4 == 0) {
          tabctr++;
          
          // Count if stores array is meron pa
          if(ctr!=stores.length) {
              // Close div tabs-#
              divHtml+='</div>';  // close tab
              divHtml+='<div id="tabsyv-'+tabctr+'" class="effectyv">'; // create new tab              
              liHtml+='<li class="margleft7yv"><a class="effecttoggleyv" href="#tabsyv-'+tabctr+'"></a></li>';
          }
        }
    }); //each
    
    // Create arrows if tabs >= 4
    if(tabctr>=4) liHtml='<li id="arrowrightian" class="margleft7yv trianglearrowrightyv"></li>'+liHtml+'<li id="arrowleftian" class="margleft7yv trianglearrowleftyv"></li>';
    // Close div
    divHtml+='</div><div class="clear"></div>';
    console.log(divHtml);
    // Add div now
    jQuery("#storescontentlist").html(divHtml);
    jQuery(".thefiltererar").html(liHtml);
           var tab_remainder = (stores.length%4) ;
       var tab_count = (stores.length/4);
       console.log("tab_count " + parseInt(tab_count) + "remain" +tab_remainder);
      
    /*** Show Next Page Pagination ***/

       $(".floatRight ul.thefiltererar").empty(); 
        
       var inc = 0;

       for( inc = 0 ; inc < tab_count; inc++){
          $(".floatRight ul.thefiltererar").append("<li class='margleft7yv ui-state-default ui-corner-top'  role='tab' tabindex="+inc+" aria-controls='tabsyv-"+inc+"' aria-labelledby='ui-id-5' aria-selected='false' aria-expanded='false'><a class='effecttoggleyv ui-tabs-anchor' tabindex="+inc+" href='#tabsyv-"+(inc+1)+"' role='presentation' tabindex='-1' id='ui-id-"+inc+"'></a></li>");
       }
       if(inc > 4 ){
          $(".floatRight ul.thefiltererar").prepend("<li id='arrowrightian' class='margleft7yv trianglearrowrightyv'></li>");
          $(".floatRight ul.thefiltererar").append("<li id='arrowleftian' class='margleft7yv trianglearrowleftyv'></li>");  
       }
            
       $("ul li.ui-state-default.ui-corner-top").eq(0).addClass("ui-tabs-active"); 
       $("ul li.ui-state-default.ui-corner-top").eq(0).addClass("ui-state-active"); 
       //this adds active state to pagination bullet
       $("ul.thefiltererar").eq(1).find("li.ui-state-default.ui-corner-top").eq(0).addClass("ui-tabs-active"); 
       $("ul.thefiltererar").eq(1).find("li.ui-state-default.ui-corner-top").eq(0).addClass("ui-state-active"); 
       //this adds active state to pagination bullet      
       $("div.effectyv").hide(); $("div.effectyv").eq(0).show();


    /*** Show Next Page Pagination ***/

    resizeIframe();
    //console.log(divHtml);
    //console.log(liHtml);
}

function pagination(page){
 
  $("div.effectyv").hide(); 
  $("div.effectyv").eq(page).show();
  $("ul.thefiltererar").eq(0).find(".ui-tabs-active").removeClass("ui-tabs-active");
  $("ul.thefiltererar").eq(1).find(".ui-tabs-active").removeClass("ui-tabs-active");

  $("ul.thefiltererar").eq(0).find(".ui-state-active").removeClass("ui-state-active");
  $("ul.thefiltererar").eq(1).find(".ui-state-active").removeClass("ui-state-active");

  $("ul.thefiltererar").eq(1).find("li.ui-state-default.ui-corner-top").eq(page).addClass("ui-tabs-active"); 
  $("ul.thefiltererar").eq(1).find("li.ui-state-default.ui-corner-top").eq(page).addClass("ui-state-active"); 

  $("ul.thefiltererar").eq(0).find("li.ui-state-default.ui-corner-top").eq(page).addClass("ui-tabs-active"); 
  $("ul.thefiltererar").eq(0).find("li.ui-state-default.ui-corner-top").eq(page).addClass("ui-state-active"); 
  
}
